import { Plugin, PluginArgs, PluginInsertArgs } from '../types/Plugin';
import { BaseRepository } from './BaseRepository';
import { relationalStore } from '@kit.ArkData';

export class PluginRepository extends BaseRepository {

  private resultSetToItem(resultSet: relationalStore.ResultSet): Plugin{
    return {
      id: resultSet.getLong(0),
      remote_id: resultSet.getLong(1),
      icon: resultSet.getString(2),
      host: resultSet.getString(3),
      name: resultSet.getString(4),
      version: resultSet.getString(5),
      type: resultSet.getString(6),
      data: resultSet.getString(7),
      create_at: resultSet.getLong(8),
      update_at: resultSet.getLong(9),
    }
  }

  async findAll(): Promise<Plugin[]> {
    const result: Plugin[] = []
    const resultSet = await this.db.querySql("select * from plugin")
    const firstRow = resultSet.goToFirstRow();
    if (firstRow) {
      do {
        const plugin: Plugin = this.resultSetToItem(resultSet)
        result.push(plugin)
      } while (resultSet.goToNextRow())
    }
    return result
  }

  async findOne(id: number): Promise<Plugin | null> {
    const resultSet = await this.db.querySql("select * from plugin where id = ?", [id])
    const firstRow = resultSet.goToFirstRow();
    if (firstRow) {
      return this.resultSetToItem(resultSet)
    }
    return null
  }

  async delete(id: number): Promise<number> {
    let predicates = new relationalStore.RdbPredicates("plugin");
    predicates.equalTo("id", id);
    return await this.db.delete(predicates)
  }

  async create(plugin: PluginArgs): Promise<number> {
    plugin.create_at = new Date().getTime()
    plugin.update_at = 0
    plugin.data = JSON.stringify(plugin.data)
    return await this.db.insert("plugin", plugin)
  }

}